﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Logger
{
    /// <summary>
    /// All other Event Logger are registered to COFEShared.MasterEventLogger.
    /// </summary>
    public class MasterEventLogger : IMasterEventLogger
    {
        #region Constructor

        public MasterEventLogger()
        {
            _eventLoggers = new Dictionary<Type, IEventLogger>();
        }

        #endregion

        #region Methods

        public void DispatchEvent(object sender, EventArgs args)
        {
            var argType = args.GetType();
            foreach (var ppair in _eventLoggers)
            {
                //if (ppair.Key == argType)
                if (ppair.Key.IsInstanceOfType(args))
                    ppair.Value.DispatchEvent(sender, args);
                return;
            }
        }


        public void RegisterEventLoggers<EA>(IEventLogger<EA> logger)
            where EA : EventArgs
        {
            lock (_eventLoggers)
            {
                if (_eventLoggers.ContainsKey(typeof(EA)))
                    _eventLoggers[typeof(EA)] = logger;
                else _eventLoggers.Add(typeof(EA), logger);
            }
        }

        public IEnumerable<IEventLog> GetEventLog(DateTime startTimeUtc, DateTime endTimeUtc)
        {
            return _eventLoggers.Values.SelectMany(logger =>
                logger.GetEventLog(startTimeUtc, endTimeUtc))
                .OrderBy((e) => e.UtcTime);
        }

        public IEnumerable<IEventLog> GetEventLog(TimeSpan pastTime)
        {
            return _eventLoggers.Values.SelectMany(logger =>
                logger.GetEventLog(pastTime))
                .OrderBy((e) => e.UtcTime);
        }

        public IEnumerable<IEventLog> GetEventLog(string sender)
        {
            return _eventLoggers.Values.SelectMany(logger =>
                logger.GetEventLog(sender))
                .OrderBy((e) => e.UtcTime);
        }

        #endregion

        #region Data

        private Dictionary<Type, IEventLogger> _eventLoggers;

        #endregion

        #region Public Properties

        public Dictionary<Type, IEventLogger> EventLoggers
        {
            get { return _eventLoggers; }
        }

        public IEventLog this[long id]
        {
            get
            {
                foreach (var l in EventLoggers.Values)
                {
                    var log = l[id];
                    if (log != null)
                        return log;
                }
                return null;
            }
        }

        #endregion





    }
}
